//
//  AppDelegate.m
//  SplunkMobile
//
//  Created by Qixin on 13-9-10.
//  Copyright (c) 2013年 Gome. All rights reserved.
//

#define IH_DEVICE_HEIGHT    [[UIScreen mainScreen] bounds].size.height
#define IH_DEVICE_WIDTH     [[UIScreen mainScreen] bounds].size.width

#import "AppDelegate.h"
#import "RootViewController.h"
#import "GMWaterMarkView.h"

@interface AppDelegate ()
{
    NSString *_oldUA;
}
// 更新URL
@property (nonatomic, copy) NSString *strUpdateUrl;
@property (nonatomic, retain) NSString *userAgent;
@end


@implementation AppDelegate


#pragma mark - ******************** View Lifecycle ********************

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor blackColor];
    
    RootViewController *vcRoot = [[RootViewController alloc] init];

    self.window.rootViewController = vcRoot;
    
    GMWaterMarkView *waterMarkView = [GMWaterMarkView shareInstance];
    waterMarkView.frame = CGRectMake(0, 60, IH_DEVICE_WIDTH, IH_DEVICE_HEIGHT-20);
    [waterMarkView showTheWaterMark];
    [self.window makeKeyAndVisible];
    
    UIApplication *app = [UIApplication sharedApplication];
    [app.keyWindow addSubview:waterMarkView];
    
    UIWebView* webView = [[UIWebView alloc] initWithFrame:CGRectZero];
    _oldUA = [webView stringByEvaluatingJavaScriptFromString:
                                 @"navigator.userAgent"];
    
    return YES;
}


- (void)applicationDidBecomeActive:(UIApplication *)application
{
    NSDictionary *dicInfo = [[NSBundle mainBundle] infoDictionary];
    NSString *strAppVersion = [dicInfo objectForKey:@"CFBundleShortVersionString"];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        

        NSString *strUrl = [NSString stringWithFormat:@"%@%@", kUpDateURL, strAppVersion];
        NSMutableURLRequest *reqUpDate = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strUrl]
                                                   cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                               timeoutInterval:20];

        
//        NSString *newUserAgent = [NSString stringWithFormat:@"%@ GomeBigdataAppSim GomeBigdata:%@", _oldUA, [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]];
        NSString *newUserAgent = [NSString stringWithFormat:@"%@ GomeBigdata:%@", _oldUA, [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]];

        [reqUpDate setValue:newUserAgent forHTTPHeaderField:@"User-Agent"];
        NSError *error;
        NSData *data = [NSURLConnection sendSynchronousRequest:reqUpDate
                                             returningResponse:nil
                                                         error:&error];
        if (data && !error)
        {
            /// ljy
//            NSString *strResultJson = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//            NSLog(@"json = %@",strResultJson);

            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data
                                                                 options:NSJSONReadingMutableContainers
                                                                   error:nil];
            self.strUpdateUrl = [dict objectForKey:@"url"];
            NSString *strDescription = [dict objectForKey:@"description"];

            if ((self.strUpdateUrl != nil)
                && (![self.strUpdateUrl isEqualToString:@""]))
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"更新提示"
                                                                        message:strDescription
                                                                       delegate:self
                                                              cancelButtonTitle:nil
                                                              otherButtonTitles:@"升级", nil];
                    [alertView show];
                });
            }
        }
    });
}


#pragma mark - ******************** View Lifecycle ********************

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) // 升级
    {
        if (self.strUpdateUrl
            && ![self.strUpdateUrl isEqualToString:@""])
        {
            NSString *itmsUrl = self.strUpdateUrl;
//              NSString *itmsUrl = [NSString stringWithFormat:@"itms-services:///?action=download-manifest&url=%@",self.updateUrl];
            NSLog(@"url= %@",itmsUrl);
            
            if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:itmsUrl]])
            {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:itmsUrl]];
            }
        }
    }
}


@end
